package io.babystar.modules.business.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.babystar.common.exception.RRException;
import io.babystar.common.utils.PageUtils;
import io.babystar.common.utils.Query;
import io.babystar.common.utils.R;
import io.babystar.common.utils.ShiroUtils;
import io.babystar.modules.business.dao.*;
import io.babystar.modules.business.entity.*;
import io.babystar.modules.business.service.CkInService;
import io.babystar.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("ckInService")
public class CkInServiceImpl extends ServiceImpl<CkInDao, CkInEntity> implements CkInService {

    @Autowired
    private CkProductDao ckProductDao;
    @Autowired
    private CkInDao ckInDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private CkOutDao ckOutDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String shopId = "";
        if(params.get("shopId")!=null){
            shopId = params.get("shopId").toString();
        }
        IPage<CkInEntity> page = this.page(
                new Query<CkInEntity>().getPage(params),
                new QueryWrapper<CkInEntity>()
                        .eq(StringUtils.isNotBlank(shopId), "shop_id", shopId)
                        .orderByDesc("create_time")
        );
        for (CkInEntity ckInEntity : page.getRecords()) {
            CkProductEntity ckProductEntity = ckProductDao.selectById(ckInEntity.getProductCode());
            if (ckProductEntity != null) {
                ckInEntity.setProductName(ckProductEntity.getProductName());
            }
            ShopEntity shopEntity = shopDao.selectById(ckInEntity.getShopId());
            if (shopEntity != null) {
                ckInEntity.setShopName(shopEntity.getShopName());
            }
            if(ckInEntity.getShopId() !=null && ckInEntity.getShopId().intValue() == -1){
                ckInEntity.setShopName("总部");
            }
            // 计算金额
            BigDecimal inNum = new BigDecimal(ckInEntity.getInNum());
            ckInEntity.setMoney(inNum.multiply(ckProductEntity.getInPrice()));
        }
        return new PageUtils(page);
    }

    @Override
    public PageUtils getByproductName(Map<String,Object> params){
        Integer count = ckInDao.getByproductNameCount(params);
        Page<CkInEntity> page = new Page<>();
        page.setTotal(count);
        Integer pageNuber = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        page.setCurrent(pageNuber);
        page.setSize(pageSize);
        Long current = page.getCurrent();
        Long size = page.getSize();
        Long currentStart = size*current - size;
        params.put("currentStart",currentStart);
        params.put("size",size);
        page.setRecords(ckInDao.getByproductName(params));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public R delete(Integer id){
        SysUserEntity sysUser = ShiroUtils.getUserEntity();
        CkInEntity ckIn = ckInDao.selectById(id);
        CkProductEntity ckProductEntity = ckProductDao.selectById(ckIn.getProductCode());
        //判断是否存在该商品
        if(ckProductEntity.getNum() != null && !"".equals(ckProductEntity.getNum())){
            //修改商品数量
            Integer productNum = ckProductEntity.getNum() - ckIn.getInNum();
            if(productNum.intValue()<0){
                return R.error("商量数量不足，回滚失败！");
            }
            ckProductEntity.setNum(productNum);
            ckProductEntity.setUpdateTime(new Date());
            ckProductEntity.setUpdator(sysUser.getUsername());
            //若更新成功再存入库单
            if(ckProductDao.updateById(ckProductEntity)>0){
                ckIn.setUpdateTime(new Date());
                ckIn.setCreator(sysUser.getUsername());
                ckInDao.deleteById(ckIn);
            }
        }else{
            return R.error("商品不存在！");
        }
        return R.ok("入库记录删除，数量回滚成功");
    }

    //申请
    @Override
    @Transactional
    public R apply(CkInEntity ckIn){
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        CkProductEntity ckProductEntity = ckProductDao.selectById(ckIn.getProductCode());
        //判断是否存在该商品
        if(ckProductEntity.getNum() != null && !"".equals(ckProductEntity.getNum())){
            Long teacherId = sysUserEntity.getParentTeacherId();
            int type = sysUserEntity.getType();
            //只有店长有权限
            if(type==2){
                // 1、分店入库申请
                TeacherEntity teacher = teacherDao.selectById(teacherId);
                //待审批
                ckIn.setStatus(0);
                ckIn.setShopId(teacher.getShopId());
                ckIn.setCreateTime(new Date());
                ckIn.setCreator(sysUserEntity.getUsername());
                ckIn.setBusinessId(ckProductEntity.getBusinessId());
                ckInDao.insert(ckIn);
                // 2、生成出库申请
                CkOutEntity ckOut = new CkOutEntity();
                ckOut.setStatus(0);
                ckOut.setShopId(teacher.getShopId());
                ckOut.setProductCode(ckIn.getProductCode());
                ckOut.setProductName(ckIn.getProductName());
                ckOut.setOutNum(ckIn.getInNum());
                ckOut.setCreateTime(new Date());
                ckOut.setRemark(ckIn.getId()+"");
                ckOut.setCreator(sysUserEntity.getUsername());
                ckOut.setBusinessId(ckProductEntity.getBusinessId());
                ckOutDao.insert(ckOut);
                return R.ok("保存成功");
            }else{
                return R.error("只有店长有权限");
            }
        }else{
            return R.error(1,"该商品不存在");
        }
    }

    //同意
    @Override
    @Transactional
    public R agree(Integer id){
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        CkOutEntity ckOut = ckOutDao.selectById(id);
        //审批通过
        ckOut.setStatus(1);
        ckOut.setUpdateTime(new Date());
        ckOut.setUpdator(sysUserEntity.getUsername());
        int result = ckOutDao.updateById(ckOut);
        if(result>0){
            CkInEntity ckIn = ckInDao.selectById(ckOut.getRemark());
            if (ckIn==null){
                throw new RRException("申请记录不存在");
            }
            ckIn.setStatus(1);
            ckIn.setUpdateTime(new Date());
            ckIn.setUpdator(sysUserEntity.getUsername());
            ckInDao.updateById(ckIn);

            CkProductEntity ckProduct = ckProductDao.selectById(ckOut.getProductCode());
            Map<String, Object> shopProductParams = new HashMap<>();
            shopProductParams.put("shop_id", ckIn.getShopId());
            shopProductParams.put("product_name", ckProduct.getProductName());
            List<CkProductEntity> inProducts = ckProductDao.selectByMap(shopProductParams);
            //判断是否存在该商品
            if(inProducts.size()>0){
                CkProductEntity inProduct = inProducts.get(0);
                // 1、增加分校商品数量
                Integer productNum = inProduct.getNum() + ckIn.getInNum();
                inProduct.setNum(productNum);
                inProduct.setUpdateTime(new Date());
                // 增加数量
                ckProductDao.updateById(inProduct);
            }else{
                ckProduct.setShopId(ckIn.getShopId());
                ckProduct.setNum(ckIn.getInNum());
                ckProduct.setCreateTime(new Date());
                ckProduct.setCreator(sysUserEntity.getUsername());
                // 增加数量
                ckProductDao.insert(ckProduct);
            }
            //减少总部
            CkProductEntity ckProductEntity = ckProductDao.selectById(ckIn.getProductCode());
            //判断是否存在该商品
            if (ckProductEntity.getNum() != null && !"".equals(ckProductEntity.getNum())) {
                // 2、减少商品数量,库存不能减为负数
                if (ckIn.getInNum() > ckProductEntity.getNum()) {
                    throw new RRException("库存不足");
                }
                Integer productNum = ckProductEntity.getNum() - ckIn.getInNum();
                ckProductEntity.setNum(productNum);
                ckProductEntity.setUpdateTime(new Date());
                //减少总部库存
                ckProductDao.updateById(ckProductEntity);
            }
            return R.ok("成功");
        } else {
            throw new RRException("没有找到记录");
        }
    }

    @Override
    public PageUtils queryCkInCountList(Map<String, Object> params) {
        Page<CkInEntity> page = new Page<>();
        Integer count = this.baseMapper.queryCkInCountListCount(params);
        page.setTotal(count);
        Integer pageNuber = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        page.setCurrent(pageNuber);
        page.setSize(pageSize);
        Long current = page.getCurrent();
        Long size = page.getSize();
        Long currentStart = size * current - size;
        params.put("currentStart", currentStart);
        params.put("size", size);
        page.setRecords(this.baseMapper.queryCkInCountList(params));

        return new PageUtils(page);
    }

}